<template>
  <div class="wrapper">
    <a-card :bordered="false">
      <a-form ref="modifyPriceForm" :model="form" :style="{ width: '100%' }" layout="horizontal" auto-label-width>
        <div class="base-info-item">
          <h4>添加积分商品</h4>
          <div class="form-item-view">
            <div style="margin: 10px;">
              <a-button type="outline"  @click="openSkuList">选择商品</a-button>
              <a-button  style="margin-left: 10px" @click="delSelectGoods" type="outline" status="danger">批量删除</a-button>
            </div>
            <a-table  row-key="skuId" :columns="columns" :data="promotionGoodsList"
              :row-selection="rowSelection" @selection-change="selectTableChange" :bordered="true">
              <template #action="{ rowIndex }">
                <a-button type="text" status="danger" @click="delGoods(rowIndex)">删除</a-button>
              </template>
              <template #settlementPrice="{ rowIndex }">
                <a-input-number v-model="promotionGoodsList[rowIndex].settlementPrice" :style="{ width: '100px' }" />
              </template>
              <template #pointsGoodsCategory="{ rowIndex }">
                <a-select :style="{ width: '100px' }" v-model="promotionGoodsList[rowIndex].pointsGoodsCategoryId">
                  <a-option v-for="item in categoryList" :key="item.id" :value="item.id"
                    @click="changeCategory(item.name, rowIndex)">{{ item.name }}</a-option>
                </a-select>
              </template>

              <template #activeStock="{ rowIndex }">
                <a-input-number v-model="promotionGoodsList[rowIndex].activeStock" :style="{ width: '100px' }" />
              </template>
              <template #points="{ rowIndex }">
                <a-input-number v-model="promotionGoodsList[rowIndex].points" :style="{ width: '100px' }" />
              </template>
            </a-table>
            <div style="height: 20px;"></div>
            <a-form-item label="兑换时间">
              <a-date-picker style="width: 200px;" format="YYYY-MM-DD HH:mm:ss" show-time v-model="form.startTime" @change="changePicker(1)" />
              -
              <a-date-picker style="width: 200px;" format="YYYY-MM-DD HH:mm:ss" show-time v-model="form.endTime" @change="changePicker(2)" />
            </a-form-item>
            <div>
              <a-button style="margin-right: 5px"  @click="closeCurrentPage">返回</a-button>
              <a-button type="primary"  :loading="submitLoading" @click="handleSubmit">提交</a-button>
            </div>
          </div>
        </div>
      </a-form>
    </a-card>
    <skuselect ref="skuSelect" @change="changSkuList" :goodsOrSku="true" :apiParams="apiParams"  :defaultGoodsSelectedList="promotionGoodsList"/>
</div>
</template>
<script setup lang='ts'>
import { ref, reactive, onMounted } from "vue"
import skuselect from '@/components/goods-sku-selector/index.vue';
import { Message } from '@arco-design/web-vue';
import useCurrentInstance from '@/hooks/useCurrentInstance';
import { getPointsGoodsCategoryList, addPointsGoods } from '@/api/promotion';
import { useRouter } from 'vue-router';
import { dayFormatHHssMM } from '@/utils/filters';

const router = useRouter()
// 表头
const columns = [
  {
    title: '商品名称',
    dataIndex: 'goodsName',
  },
  {
    title: 'SKU编码',
    dataIndex: 'skuId',
  },
  {
    title: '店铺名称',
    dataIndex: 'storeName',
  },
  {
    title: '商品价格',
    dataIndex: 'price',
  },
  {
    title: '库存',
    dataIndex: 'quantity',
  },
  {
    title: '结算价格',
    dataIndex: 'settlementPrice',
    slotName: 'settlementPrice'
  },
  {
    title: '分类',
    dataIndex: 'pointsGoodsCategory',
    slotName: 'pointsGoodsCategory'
  },
  {
    title: '活动库存',
    dataIndex: 'activeStock',
    slotName: 'activeStock'
  },
  {
    title: '兑换积分',
    dataIndex: 'points',
    slotName: 'points'

  },
  {
    title: '操作',
    dataIndex: 'action',
    slotName: 'action'
  },
]
//  获取modal
const modal = useCurrentInstance().globalProperties?.$modal;
const skuSelect = ref(null) as any// 商品选择器
const form = ref({
  promotionGoodsList: [], // 活动商品列表
  startTime: '',
  endTime: ''
})
const submitLoading = ref<boolean>(false)  // 添加或编辑提交状态
const rowSelection = reactive<any>({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: false,
});
const categoryList = ref([]) as any// 分类列表
const promotionGoodsList = ref([]) as any// 活动商品列表
const selectedGoods = ref<any>([])  // 已选商品列表，便于删除
const apiParams = {
  marketEnable: 'UPPER',
  authFlag: 'PASS'
}
// 选择的商品
const changSkuList = (val: any) => {
  const list: any = []
  val.forEach((e: any) => {
    const obj = {
      settlementPrice: e.settlementPrice || 0,
      pointsGoodsCategoryId: e.pointsGoodsCategoryId || '',
      pointsGoodsCategoryName: e.pointsGoodsCategoryName || "",
      activeStock: e.activeStock || 0,
      points: e.points || 0,
      skuId: e.id,
      goodsId: e.goodsId,
      originalPrice: e.price || 0,
      thumbnail: e.thumbnail || "",
      goodsName: e.goodsName || "",
      quantity: e.quantity || "",
      storeName: e.storeName || "",
      price: e.price || ""
    }
    list.push(obj);
  })
  promotionGoodsList.value = list
}
// 选择商品
const openSkuList = () => {
  skuSelect.value.modalData.visible = true
}
// 传过来的商品
const selectTableChange = (val: any) => {
  selectedGoods.value = val
}
// 单选删除
const delGoods = (idx: any) => {
  promotionGoodsList.value.splice(idx, 1)
}
// 批量删除
const delSelectGoods = () => {
  if (selectedGoods.value.length <= 0) {
    Message.warning('您还未选择要删除的数据');
    return
  }
  modal.confirm({
    title: '确认删除',
    content: `您确认要删除所选商品吗?`,
    alignCenter: false,
    onOk: async () => {
      promotionGoodsList.value = promotionGoodsList.value.filter((item: any) => {
        return !selectedGoods.value.includes(item.skuId);
      });
    },
  });
}
// 提交
const handleSubmit = () => {
  let params = promotionGoodsList.value
  if (!params || params.length == 0) {
    Message.warning('请选择指定商品');
    return
  }
  // 校验积分商品参数
  for (let i = 0; i < params.length; i++) {
    if (!params[i].activeStock) {
      Message.warning('请填写活动库存');
      return
    }
    if (!params[i].points) {
      Message.warning('请填写兑换积分');
      return
    }
  }

  if (!form.value.startTime || !form.value.endTime) {
    Message.warning('请选择兑换时间');
    return
  }

  submitLoading.value = true
  params = params.map((item: any) => {
    return {
      ...item,
      startTime: dayFormatHHssMM(form.value.startTime),
      endTime: dayFormatHHssMM(form.value.endTime)
    }
  })
  addPointsGoods(params).then((res: any) => {
    submitLoading.value = false
    if (res.data.success) {
      Message.success('积分商品创建成功');
      router.push({ name: 'integrate-goods' })
    }
  })
}
// 选择日期
const changePicker = (val: any) => {
  // console.log(new Date().toISOString());

  
}
// 选择商品
const changeCategory = (val: string, index: number) => {
  promotionGoodsList.value[index].pointsGoodsCategoryName = val
}
// 获取商品分类
const init = async () => {
  const res = await getPointsGoodsCategoryList();
  if (res.data.success) {
    categoryList.value = res.data.result.records
  }
}
// 返回
const closeCurrentPage = () => {
  router.push({ name: 'integrate-goods' })
}
onMounted(() => {
  init()
})
</script>

<style lang="less" scoped>
h4 {
  margin-bottom: 10px;
  padding: 0 10px;
  border: 1px solid #ddd;
  background-color: #f8f8f8;
  font-weight: bold;
  color: #333;
  font-size: 14px;
  line-height: 40px;
  text-align: left;
}

.describe {
  font-size: 12px;
  margin-left: 10px;
  color: #999;
}

.wrapper {
  min-height: 800px;
}



:deep(.arco-card-body) {
  padding: 0;
}
</style>
